<template>
  <div>
    <a-modal
      v-model:open="modal.theme"
      title="主题配置"
      @cancel="handleCancel(true)"
      :maskClosable="false"
    >
      <div class="theme-pop">
        <div v-for="idx of 2" :key="idx">
          <div class="theme-title">
            添加{{ idx == 1 ? "文字框" : "背景图片" }}:
          </div>
          <a-upload
            list-type="picture-card"
            :show-upload-list="false"
            :data="{ idx }"
            :customRequest="upBgOver"
          >
            <template v-if="idx == 1">
              <div class="upload-card" v-if="!reviewImg1">
                <plus-outlined />
                <div style="margin-top: 8px">上传图片</div>
              </div>
              <img
                class="img-class"
                style="width: 100%"
                :src="reviewImg1"
                v-else
              />
            </template>
            <template v-else>
              <div class="upload-card" v-if="!reviewImg2">
                <plus-outlined />
                <div style="margin-top: 8px">上传图片</div>
              </div>
              <img
                class="img-class"
                style="width: 100%"
                :src="reviewImg2"
                v-else
              />
            </template>
          </a-upload>
          <div class="theme-tips" v-if="idx == 1">
            温馨提示：<br />
            为保证展示效果请将图片控制在<span>2736*1476</span>像素内，PNG格式（透明背景）的图片
          </div>
          <div class="theme-tips" v-else>
            温馨提示：<br />
            为保证展示效果请上传<span>3840*2160</span>像素，JPG格式，大小≤1MB以下的图片
          </div>
        </div>
      </div>
      <template #footer>
        <a-button key="back" @click="handleCancel(true)">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleOk(1)"
          >提交</a-button
        >
      </template>
    </a-modal>

    <a-modal
      v-model:open="modal.select"
      title="奖项配置"
      @cancel="handleCancel(true)"
      :maskClosable="false"
    >
      <div class="select-pop">
        <div class="select-item">
          <div class="select-title">奖项名称：</div>
          <a-input
            v-model:value="jxName"
            placeholder="输入奖项名称"
            allow-clear
          />
          <a-button
            key="submit"
            type="primary"
            :disabled="!jxName"
            :loading="loading"
            @click="handleOk(2)"
            >添加</a-button
          >
        </div>
        <div class="btn-group" v-if="gData.length > 0">
          <div @click="delSelect"><DeleteOutlined />删除</div>
          <span>拖动文字进行排序</span>
        </div>
        <div class="tree">
          <a-tree
            class="draggable-tree"
            draggable
            block-node
            checkable
            v-if="gData.length > 0"
            :tree-data="gData"
            @drop="onDrop"
            @check="checkChange"
          />
        </div>
      </div>
      <template #footer>
        <a-button key="back" @click="handleCancel(true)">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="selectSort"
          >确认</a-button
        >
      </template>
    </a-modal>

    <a-modal
      v-model:open="modal.gift"
      title="奖品内容配置"
      @cancel="handleCancel(true)"
      :maskClosable="false"
    >
      <div class="gift-pop">
        <div class="gift-item">
          <div class="gift-title">奖品名称：</div>
          <a-input
            v-model:value="defaultData.name"
            placeholder="请输入奖品名称"
            allow-clear
          />
        </div>
        <div class="gift-item">
          <div class="gift-title">奖品配图：</div>
          <a-upload
            list-type="picture-card"
            :show-upload-list="false"
            :customRequest="upBgOver"
            :data="{ idx: 1 }"
          >
            <div class="upload-card" v-if="!reviewImg1">
              <plus-outlined />
              <div style="margin-top: 8px">上传图片</div>
            </div>
            <img
              class="img-class"
              style="width: 100%"
              :src="reviewImg1"
              v-else
            />
          </a-upload>
          <!-- <div class="theme-tips">
            温馨提示：<br />
            为保证展示效果请上传<span>XX*XX像素，JPG</span>格式的图片
          </div> -->
        </div>
      </div>
      <template #footer>
        <a-button key="back" @click="handleCancel(true)">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleOk(3)"
          >提交</a-button
        >
      </template>
      <p></p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, watch } from "vue";
import { Modal, message } from "ant-design-vue";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import * as Api from "@req/api";
const [messageApi, contextHolder] = message.useMessage();
const open = ref(false);
const loading = ref(false);
const giftName = ref("");
const jxName = ref("");
const reviewImg1 = ref("");
const reviewImg2 = ref("");
const selectKeys = ref([]);
const emit = defineEmits(["closePop"]);
const modal = ref({
  theme: false,
  select: false,
  gift: false,
});

const defaultData = ref({
  id: "",
  name: "",
  url: "",
  zt_url: "",
  img_url: "",
  l_type: "",
});

const props = defineProps({
  popType: {
    type: String,
    default: "",
  },
  eidtData: {
    type: [Object, null],
    default: {},
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  areasList: {
    type: Array,
    default: [],
  },
});

watch(
  () => props.eidtData,
  (newVal) => {
    if (newVal) {
      defaultData.value = newVal;
      getImgUrl(1);
      getImgUrl(2);
    } else {
      defaultData.value = {
        id: "",
        name: "",
        url: "",
        zt_url: "",
        img_url: "",
        l_type: "",
      };
    }
  }
);

watch(
  () => props.areasList,
  (newVal) => {
    if (newVal)
      gData.value = newVal.map((v) => {
        return { title: v.label, key: v.value };
      });
  }
);

watch(
  () => props.popType,
  (newVal) => {
    reviewImg1.value = "";
    reviewImg2.value = "";
    if (newVal) modal.value[newVal] = true;
  }
);

const gData = ref([]);

const handleOk = (type) => {
  if (type == 2) {
    defaultData.value.name = jxName.value;
  } else {
    defaultData.value.img_url = defaultData.value.url;
  }
  if (type == 1 && !defaultData.value.img_url) {
    message.error("请上传文字框!");
    return;
  }
  if (type == 1 && !defaultData.value.zt_url) {
    message.error("请上传背景!");
    return;
  }
  if (type == 3 && !defaultData.value.name) {
    message.error("请填写产品名称!");
    return;
  }
  if (type == 3 && !defaultData.value.img_url) {
    message.error("请上传产品图片!");
    return;
  }
  defaultData.value.l_type = type;
  delete defaultData.value.url;
  if (props.isEdit) {
    delete defaultData.value.l_type;
    Api.editLottery(defaultData.value).then((res) => {
      console.log(res);
      if (res.code == 0) {
        if (type != 2) handleCancel();
        if (type == 2) emit("reload");
      }
    });
  } else {
    Api.createLottery(defaultData.value).then((res) => {
      console.log(res);
      if (res.code == 0) {
        if (type != 2) handleCancel();
        if (type == 2) emit("reload");
      }
    });
  }
  defaultData.value = {
    id: "",
    name: "",
    url: "",
    zt_url: "",
    img_url: "",
    l_type: "",
  };
  jxName.value = "";
};

const selectSort = () => {
  let oldIdlist = props.areasList.map((v) => v.value);
  let nowIdList = gData.value.map((v) => v.key);
  if (JSON.stringify(oldIdlist) != JSON.stringify(nowIdList)) {
    Api.sortLottery({ ids: nowIdList }).then((res) => {
      handleCancel();
    });
  } else {
    handleCancel();
  }
};

const upBgOver = (e) => {
  const list = ["image/jpeg", "image/png"];
  if (!list.includes(e.file.type)) {
    message.error("请上传图片格式!");
    return;
  }
  let forms = new FormData();
  forms.append("file", e.file);
  Api.fileUpLoad(forms).then((res) => {
    if (!res.code == 0) return;
    if (e.data.idx == 1) {
      defaultData.value.url = res.data.url;
    } else {
      defaultData.value.zt_url = res.data.url;
    }
    getImgUrl(e.data.idx, "up");
  });
};

const getImgUrl = async (idx, type) => {
  const url = idx == 1 ? defaultData.value.url : defaultData.value.zt_url;
  if (!url) return "";
  if (idx == 1) {
    reviewImg1.value = await Api.getFileUrl(url);
  } else {
    reviewImg2.value = await Api.getFileUrl(url);
  }
  if (type) {
    message.success("上传成功！");
  }
};

const handleCancel = (isClose) => {
  modal.value.theme = false;
  modal.value.select = false;
  modal.value.gift = false;
  emit("closePop", !!isClose);
};

const checkChange = (v) => {
  selectKeys.value = v;
};

const delSelect = () => {
  if (selectKeys.value.length <= 0) return;

  Modal.confirm({
    title: "确认删除吗？",
    content: "删除后不可恢复，需重新配置",
    okText: "确认",
    cancelText: "取消",
    onOk() {
      Promise.all(selectKeys.value.map((v) => delApi(v))).then((res) => {
        emit("reload");
        setTimeout(() => {
          Modal.success({
            title: "提示",
            content: "删除成功",
            okText: "确认",
          });
        }, 500);
      });
    },
  });
};

const delApi = (id) => {
  return Api.delLottery({ id });
};

const onDrop = (info) => {
  const dropKey = info.node.key;
  const dragKey = info.dragNode.key;
  const dropPos = info.node.pos.split("-");
  const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
  const loop = (data, key, callback) => {
    data.forEach((item, index) => {
      if (item.key === key) {
        return callback(item, index, data);
      }
      if (item.children) {
        return loop(item.children, key, callback);
      }
    });
  };
  const data = [...gData.value];

  // Find dragObject
  let dragObj;
  loop(data, dragKey, (item, index, arr) => {
    arr.splice(index, 1);
    dragObj = item;
  });
  if (!info.dropToGap) {
    // Drop on the content
    loop(data, dropKey, (item) => {
      item.children = item.children || [];
      /// where to insert 示例添加到头部，可以是随意位置
      item.children.unshift(dragObj);
    });
  } else if (
    (info.node.children || []).length > 0 &&
    // Has children
    info.node.expanded &&
    // Is expanded
    dropPosition === 1 // On the bottom gap
  ) {
    loop(data, dropKey, (item) => {
      item.children = item.children || [];
      // where to insert 示例添加到头部，可以是随意位置
      item.children.unshift(dragObj);
    });
  } else {
    let ar = [];
    let i = 0;
    loop(data, dropKey, (_item, index, arr) => {
      ar = arr;
      i = index;
    });
    if (dropPosition === -1) {
      ar.splice(i, 0, dragObj);
    } else {
      ar.splice(i + 1, 0, dragObj);
    }
  }
  gData.value = data;
};
</script>

<style lang="postcss" scoped>
.theme-pop {
  display: flex;
  justify-content: space-between;
  .theme-title {
    margin-bottom: 12px;
  }

  :deep .ant-upload-picture-card-wrapper .ant-upload.ant-upload-select {
    width: 200px;
    height: 100px;
    color: gray;
    overflow: hidden;
  }
  .img-class {
    width: 200px;
    height: 100px;
    object-fit: cover;
  }
}

.theme-tips {
  width: 200px;
  margin-bottom: 20px;
  font-size: 12px;
  span {
    color: #00b6e8;
  }
}
.select-pop {
  .select-item {
    display: flex;
    margin-bottom: 12px;
    .select-title {
      flex: 0 0 80px;
      line-height: 32px;
    }
    button {
      margin-left: 12px;
    }
  }
  .btn-group {
    display: flex;
    margin-bottom: 12px;
    align-items: center;
    div {
      flex: 0 0 50px;
      margin-right: 10px;
      cursor: pointer;
      &:first-child {
        margin-left: 25px;
      }
      span {
        margin-right: 5px;
      }
    }
    & > span {
      display: block;
      margin-right: 25px;
      margin-left: auto;
      cursor: pointer;
      font-size: 12px;
    }
  }
  &:deep .ant-tree {
    border: 1px solid #d3d3d3;
  }
}

.gift-item {
  display: flex;
  margin-bottom: 24px;
  .gift-title {
    flex: 0 0 80px;
    line-height: 32px;
  }
  .theme-tips {
    width: 200px;
    align-self: center;
    margin-left: 24px;
  }
  :deep .ant-upload-wrapper {
    width: 102px;
  }
}
</style>